package com.hyyt.shopjsp.finance.controller;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hyyt.shopjsp.util.common.EnumUtils;
import com.hyyt.shopjsp.util.export.ExportExcel;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hyyt.shopjsp.basic.pojo.BasicCustomer;
import com.hyyt.shopjsp.basic.pojo.BasicUsers;
import com.hyyt.shopjsp.basic.service.IBasicCustomerService;
import com.hyyt.shopjsp.basic.service.IBasicUsersService;
import com.hyyt.shopjsp.common.controller.BaseController;
import com.hyyt.shopjsp.finance.pojo.ShopDrawing;
import com.hyyt.shopjsp.finance.service.IShopDrawingService;
import com.hyyt.shopjsp.util.common.Page;
import com.hyyt.shopjsp.util.common.ResultMsg;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.util.json.FastJsonUtils;

/**
 * Copyright (c) 2017 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
 * @author Wang Youchun on 2017/4/01 0024下午 17:59.
 */
@Controller
@RequestMapping("/back/customer/drawing")
public class ShopDrawingController extends BaseController {
	private Logger log = Logger.getLogger(ShopDrawingController.class);
	private String basePath = "/back/shop/customer/";
	
	@Resource
	private IShopDrawingService drawingService;//提现记录service
	@Resource
	private IBasicCustomerService basicCustomerService;//会员service
	@Resource
	private IBasicUsersService basicUsersService;//后台管理员service
	/**
     * 进入会员余额提现页面
	 *
     * @return 进入指定页面
     */
    @RequestMapping("gotoDrawingPageList")
    public String gotoDrawingPageList() {
        return basePath + "drawingList";
    }

	/**
	 * 金币明细列表
	 * @param page
	 * @param response
	 */
	@RequestMapping(value="drawingPageList",method=RequestMethod.POST)
	@ResponseBody
	public void drawingPageList(String drawingCode,String startTime,String endTime,String state,Page page, HttpServletResponse response){
		Map<String, Object>param=new HashMap<>();
		if(Utils.objectIsNotEmpty(drawingCode)){
			param.put("drawingCode", drawingCode.trim());
		}
		if(Utils.objectIsNotEmpty(state)){
			param.put("state", state);
		}
		if(Utils.objectIsNotEmpty(startTime)){
			param.put("startTime", startTime);
		}
		if(Utils.objectIsNotEmpty(endTime)){
			param.put("endTime", endTime);
		}
		param.put("sortColumns", "drawingId desc");
		int totalRecordCount =drawingService.countShopDrawing(param);
		page.setPageInfo(page.getPageSize(), totalRecordCount, page.getCurrentPage());
		List<ShopDrawing> drawingList =drawingService.queryShopDrawing(param, page.getPageRecordBeginIndex(), page.getPageSize());
		param.clear();
		param.put("total", totalRecordCount);// total键 存放总记录数，必须的
		param.put("rows", drawingList);// rows键 存放每页记录 list
		ResultMsg.create(param, response);  //把内容发送到页面
	}

	/**
	 * 获得金币明细对象
	 * @param drawingId
	 * @return
	 */
	@RequestMapping(value="getDrawingObject",method=RequestMethod.POST)
	@ResponseBody
	public ResultMsg getDrawingObject(Integer drawingId){
		Map<String, Object> param=new HashMap<>();
		if(Utils.objectIsNotEmpty(drawingId)){
			ShopDrawing shopDrawing = drawingService.loadShopDrawing(drawingId);
			if(Utils.objectIsNotEmpty(shopDrawing.getUpdateUserId())){
				BasicUsers basicUsers = basicUsersService.loadBasicUsers(shopDrawing.getUpdateUserId());
				param.put("userName", basicUsers.getUserName());
			}
			if(Utils.objectIsNotEmpty(shopDrawing.getCustomerId())){
				BasicCustomer customer = basicCustomerService.loadBasicCustomer(shopDrawing.getCustomerId());
				param.put("customerName", customer.getLoginName());
			}
			if(Utils.objectIsNotEmpty(shopDrawing)){
				param.put("drawing", shopDrawing);
				return ResultMsg.create(true, null, FastJsonUtils.toJSONString(param));
			}
			else {
				return ResultMsg.create(false);
			}
		}else {
			return ResultMsg.create(false);
		}
	}

	/**
     * 审核会员余额提现
     *
     * @param drawingId
     * @param remarks
     * @param state
     * @return
     */
    @RequestMapping(value = "saveOrUpdateDrawingState", method = RequestMethod.POST)
    @ResponseBody
	public ResultMsg saveOrUpdateDrawingState(String drawingId,String remarks,String state) {
		boolean flag=false;
    	if (Utils.objectIsNotEmpty(drawingId) && Utils.objectIsNotEmpty(remarks) && Utils.objectIsNotEmpty(state)) {
			ShopDrawing drawing = drawingService.loadShopDrawing(Integer.parseInt(drawingId));
			if(Utils.objectIsNotEmpty(drawing)&&Utils.objectIsNotEmpty(drawing.getDrawingId())){
				drawing.setState(Integer.valueOf(state));//状态
				drawing.setRemarks(remarks);//备注
				if("3".equals(state)){//已发放
					Timestamp date =new Timestamp(System.currentTimeMillis());//获取当前系统timestamp
					drawing.setUpdateTime(date);
					BasicUsers basicUsers = getSessionUsers();
					drawing.setUpdateUserId(basicUsers.getUsersId());
				}
				drawingService.updateShopDrawing(drawing);
				flag=true;
			}
			return ResultMsg.create(flag);
		}else {
			return ResultMsg.create(false);
		}
	}

	/**
	 * 导出会员余额提现excel
	 * @param drawingCode
	 * @param startTime
	 * @param endTime
	 * @param state
	 * @param request
	 * @param response
	 */
	@RequestMapping("exportDrawingExcel")
	public void exportDrawingExcel(String drawingCode, String startTime, String endTime, String state, HttpServletRequest request, HttpServletResponse response){
		Map<String, Object>param=new HashMap<>();
		if(Utils.objectIsNotEmpty(drawingCode)){
			param.put("drawingCode", drawingCode.trim());
		}
		if(Utils.objectIsNotEmpty(state)){
			param.put("state", state);
		}
		if(Utils.objectIsNotEmpty(startTime)){
			param.put("startTime", startTime);
		}
		if(Utils.objectIsNotEmpty(endTime)){
			param.put("endTime", endTime);
		}
		param.put("sortColumns", "drawingId desc");
		List<ShopDrawing> drawingList =drawingService.queryShopDrawing(param);
		SimpleDateFormat formatter = new SimpleDateFormat(EnumUtils.DataFormat.Y_M_D_H_m_s.getValue());
		List<Map<String,Object>> drawing = new ArrayList<>();
		if(drawingList!=null&&drawingList.size()>0){
			for (ShopDrawing shopDrawing : drawingList) {
				Map<String,Object> map = new HashMap<>();
				map.put("drawingCode", shopDrawing.getDrawingCode());
				map.put("drawingAmount", shopDrawing.getDrawingAmount());
				map.put("remarks", shopDrawing.getRemarks());
				switch (shopDrawing.getState()){
					case 1:
						map.put("state","已提交");
						break;
					case 2:
						map.put("state","已审核");
						break;
					case 3:
						map.put("state","已发放");
						break;
				}
				map.put("createTime", shopDrawing.getCreateTime());
				map.put("updateTime", shopDrawing.getUpdateTime());
				drawing.add(map);
			}
		}
		String fileName ="会员余额提现";
		String columnNames[] = {"提现编号","提现金额(元)","备注","状态","申请时间","发放时间"};
		String keys[] = {"drawingCode","drawingAmount","remarks","state","createTime","updateTime"};
		try {
			ExportExcel.download(fileName,drawing,columnNames,keys,request,response);
		} catch (IOException e) {
			logger.error("导出Excel失败！");
		}

	}
}